package com.orhon.smartcampus.modules.teacher.mutation;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.SchoolsDao;
import com.orhon.smartcampus.modules.teacher.dao.DoctoralSupervisorDao;
import com.orhon.smartcampus.modules.teacher.dao.TInformationDao;
import com.orhon.smartcampus.modules.teacher.entity.DoctoralSupervisor;
import com.orhon.smartcampus.modules.teacher.gqlInputModel.GQLDoctoralSupervisorInput;
import com.orhon.smartcampus.modules.teacher.inputMapper.DoctoralSupervisorInputMapper;
import com.orhon.smartcampus.modules.user.dao.TokenService;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class AddDoctoralSupervisorMutation implements DataFetcher {

	@Autowired
	DoctoralSupervisorDao doctoralSupervisorDao;

	@Autowired
	TInformationDao tInformationDao;

	@Autowired
	SchoolsDao schoolsDao;

	@Autowired
	TokenService tokenService;

	/**
	 * 添加博导信息
	 * editor : ths
	 */
	@Override
	public Object get(DataFetchingEnvironment environment) throws Exception {

		//String token = (String) SecurityUtils.getSubject().getPrincipal();
		String token = tokenService.getSystemToken();
		Long schoolId = JwtUtils.getSchoolId(token);
		GQLDoctoralSupervisorInput input = DoctoralSupervisorInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));

		DoctoralSupervisor doctoralSupervisor = null;

		if (input.getId() != null) {
			doctoralSupervisor = doctoralSupervisorDao.get(DoctoralSupervisor.class, input.getId());
			doctoralSupervisor.setUpdatedAt(new Date());
		} else {
			doctoralSupervisor = new DoctoralSupervisor();
			doctoralSupervisor.setCreatedAt(new Date());
		}
	    if(schoolId != null){

			doctoralSupervisor.setSchool_id(schoolId);
		}
	    if(input.getTeacher_id() != null){

			doctoralSupervisor.setTeacher_id(input.getTeacher_id());
		}
	    if(input.getIsteach() != null){

			doctoralSupervisor.setIsteach(input.getIsteach());
		}
	    if(input.getYears() != null){

			doctoralSupervisor.setYears(input.getYears());
		}
	    if(input.getImage() != null){

			doctoralSupervisor.setImage(input.getImage());
		}
	    if(input.getShenhe() != null){

			doctoralSupervisor.setShenhe(input.getShenhe());
		}
		try{
			doctoralSupervisorDao.saveOrUpdate(doctoralSupervisor);
		}
		catch (Exception e){
			return Result.error(500,""+e);
		}
		return Result.ok();
	}
}

